class PlansController < ApplicationController
  
  before_filter :login_required
  require_role ['financiero'], :only=>[:destroy]
  
  def index
    store_location
    list
    render :action => 'list'
  end
 
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    store_location
    search
  end

  def alumnos_sin_plan
    store_location
    @alumnos_sin_plan = Persona.find_alumnos(:all, :conditions=>"NOT EXISTS ( SELECT * FROM plans WHERE personas.id=plans.alumno_id AND plans.ini<=CURDATE() AND plans.fin>=CURDATE() )")
  end

  def proximos_a_vencer
    store_location
    @planes_prox_vencer = Plan.find(:all,:conditions=>"DATEDIFF(fin,CURDATE())<31 AND DATEDIFF(fin,CURDATE())>0", :order=>"fin ASC")
  end

  def search
    @nombre = params[:nombre] if params[:nombre]!=''
    @alumno_str = params[:alumno_str] if params[:alumno_str]!=''

    query = "1"
    binds = Array.new
    if @nombre then
      query << " AND nombre LIKE ?"
      binds << "#{@nombre}%"
    end
    if @alumno_str then
      join = 'JOIN personas ON personas.id = plans.alumno_id'
      tokens = @alumno_str.strip.split(' ',2)
      query << " AND ((nombres like ? and apellidos like ?) or (apellidos like ? and nombres like ?))"
      binds << "#{tokens[0]}%"
      binds << "#{tokens[1]}%"
      binds << "#{tokens[0]}%"
      binds << "#{tokens[1]}%"
    end
    
    @plan_pages, @plans = paginate :plans, :per_page => 20, :order =>'ini DESC', :conditions=>[query,binds].flatten, :join=>join
    @page, @lnk_from, @lnk_to = numeros_pagina @plan_pages
  end

  def new
    @plan = Plan.new
    @plan.ini = Date.today()
    # preseteo el alumno segun lo que llego por params
    @plan.alumno_id = params[:plan_alumno] if params[:plan_alumno]
  end

  def create
    dias_meses = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    @plan = Plan.new(params[:plan])
    if params[:cant] and params[:monto] and params[:primer_vto] then
      i = dif = 0
      while i < params[:cant].to_i
        ticket = @plan.tickets.build(:monto=>params[:monto],:vto=>(params[:primer_vto]))
        ticket.vto += dif+dias_meses[ticket.vto.month-1]+(((ticket.vto.month==2) and ticket.vto.leap?)?1:0)
        dif += dias_meses[ticket.vto.month-1]+(((ticket.vto.month==2) and ticket.vto.leap?)?1:0)
        i+=1
      end
    end
    if @plan.save
      flash[:success] = 'Plan creado exitosamente.'
      redirect_back_or_default :action => 'show', :controller=>'alumnos', :id=>@plan.alumno
    else
      render :action => 'new'
    end
  end

  def edit
    @plan = Plan.find(params[:id])
  end

  def update
    @plan = Plan.find(params[:id])
    if @plan.update_attributes(params[:plan])
      flash[:success] = 'Plan modificado con &eacute;xito.'
      redirect_back_or_default :action => 'show', :id => @plan
    else
      render :action => 'edit'
    end
  end

  def destroy
    Plan.find(params[:id]).destroy
    flash[:success] = 'Plan eliminado con &eacute;xito.'
    redirect_back_or_default :action => 'list'
  end
  
end
